package com.demo.repository;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.demo.entity.MoneyRank;
import com.demo.entity.Sale;
import javafx.beans.binding.ObjectExpression;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import com.demo.entity.ProductRecord;
import org.springframework.data.repository.query.Param;

/**
 * Created by lenovo on 2017/6/21.
 */
public interface ProductRecordRepo extends PagingAndSortingRepository<ProductRecord, Integer> {

	public List<ProductRecord> findByUserIdAndCreateTimeAfterAndCreateTimeBefore(Integer userId, Date begin, Date end);

	public List<ProductRecord> findByUserIdOrderByCreateTimeDesc(Integer userId, Pageable pageRequest);

	@Query(value="SELECT r.user_name, SUM(r.money) AS 'money' FROM product_record r GROUP BY r.user_name ORDER BY money DESC",nativeQuery=true)
	public List<Map<String, Object>> getGroupByUserIdOrderBySumMoney();

    @Query(value="SELECT r.product_name, count(*) AS 'total', SUM(r.money) AS 'money' FROM product_record r GROUP BY r.product_name ORDER BY total DESC",nativeQuery=true)
    public List<Map<String, Object>> getGroupByProductIdOrderBySumMoney();

    @Query(value="SELECT rownum rank,user_id,money\n" +
            "FROM\n" +
            "(\n" +
            "SELECT @rownum\\:=@rownum+1 rownum, user_id,money\n" +
            "FROM ( \n" +
            "SELECT user_id,SUM(money) money,@rownum\\:=0 FROM product_record GROUP BY user_id ORDER BY SUM(money) DESC\n" +
            ") t \n" +
            ") t WHERE user_id=:userId",nativeQuery=true)
	public List<Object[]> findRankByAmount(@Param("userId") Integer userId);
}
